#pragma once
#include "../common/dispatcher.hpp"
#include "requestor.hpp"
#include "rpc_caller.hpp"
#include "rpc_registry.hpp"
#include "rpc_topic.hpp"

namespace jsonrpc
{
    namespace client
    {
        // 1.服务注册客户端
        class RegistryClient
        {
        public:
            using ptr = std::shared_ptr<RegistryClient>;
            // 传入注册中心的地址信息, 用于连接注册中心
            RegistryClient(const std::string &ip, int port)
                : _requestor(std::make_shared<Requestor>())
                , _provider(std::make_shared<client::Provider>(_requestor))
                , _dispatcher(std::make_shared<Dispatcher>())
            {
                // 1.向dispatcher注册类型的回调函数
                auto rsp_cb = std::bind(&client::Requestor::onResponse, _requestor.get(), std::placeholders::_1, std::placeholders::_2);
                _dispatcher->registerHandler<BaseMessage>(MType::RSP_SERVICE, rsp_cb); // 收到注册中心的响应所进行的回调

                // 2.客户端设置dispatcher的onMessage回调函数(实现根据类型调用对应回调函数)
                auto message_cb = std::bind(&Dispatcher::onMessage, _dispatcher.get(), std::placeholders::_1, std::placeholders::_2);
                _client = ClientFactory::create(ip, port);
                _client->setMessageCallback(message_cb);
                _client->connect();
            }

        public:
            // 向外提供的服务注册接口
            bool registryMethod(const std::string &method, const Address &host)
            {
                return _provider->registryMethod(_client->connection(), method, host);
            }

            // 向注册中心发送心跳包
            void sendHeartbeat(const BaseMessage::ptr& req)
            {
                // _provider发送心跳包
                _provider->sendHeartbeat(_client->connection(), req);
            }

        private:
            Requestor::ptr _requestor;
            client::Provider::ptr _provider;
            Dispatcher::ptr _dispatcher;
            BaseClient::ptr _client;
        };

        // 2.服务发现客户端
        class DiscoveryClient
        {
        public:
            using ptr = std::shared_ptr<DiscoveryClient>;
            // 传入注册中心的地址信息, 用于连接注册中心
            DiscoveryClient(const std::string &ip, int port, const Discoverer::OfflineCallback &cb)
                : _requestor(std::make_shared<Requestor>())
                , _discoverer(std::make_shared<client::Discoverer>(_requestor, cb))
                , _dispatcher(std::make_shared<Dispatcher>())
            {
                // 1.向dispatcher注册类型的回调函数
                auto rsp_cb = std::bind(&client::Requestor::onResponse, _requestor.get(), std::placeholders::_1, std::placeholders::_2);
                auto req_cb = std::bind(&client::Discoverer::onServiceRequest, _discoverer.get(), std::placeholders::_1, std::placeholders::_2);
                _dispatcher->registerHandler<BaseMessage>(MType::RSP_SERVICE, rsp_cb);
                _dispatcher->registerHandler<ServiceRequest>(MType::REQ_SERVICE, req_cb);
                // 2.设置客户端的回调函数
                auto message_cb = std::bind(&Dispatcher::onMessage, _dispatcher.get(), std::placeholders::_1, std::placeholders::_2);
                _client = ClientFactory::create(ip, port);
                _client->setMessageCallback(message_cb);
                _client->connect();
            }

        public:
            // 向外提供的服务发现接口
            bool serviceDiscovery(const std::string &method, Address &host)
            {
                return _discoverer->serviceDiscovery(_client->connection(), method, host);
            }

        private:
            Requestor::ptr _requestor;
            client::Discoverer::ptr _discoverer;
            Dispatcher::ptr _dispatcher;
            BaseClient::ptr _client;
        };

        // 3.rpc客户端
        class RpcClient
        {
        public:
            using ptr = std::shared_ptr<RpcClient>;
            // 传入注册中心的地址信息, 用于连接注册中心
            RpcClient(bool enableDiscovery, const std::string &ip, int port)
                : _enableDiscovery(enableDiscovery), _requestor(std::make_shared<Requestor>())
                , _dispatcher(std::make_shared<Dispatcher>())
                , _caller(std::make_shared<jsonrpc::client::RpcCaller>(_requestor))
            {
                // 1.向dispatcher注册类型的回调函数 (针对rpc请求后的响应进行的回调处理)
                auto rsp_cb = std::bind(&client::Requestor::onResponse, _requestor.get(), std::placeholders::_1, std::placeholders::_2);
                _dispatcher->registerHandler<BaseMessage>(MType::RSP_RPC, rsp_cb);

                // 如果启用了服务发现，地址信息是注册中心的地址，是服务发现客户端需要连接的地址，则通过地址信息实例化discovery_client
                // 如果没有启用服务发现，则地址信息是服务提供者的地址，则直接实例化好rpc_client
                if (_enableDiscovery)
                {
                    auto offline_cb = std::bind(&RpcClient::delClient, this, std::placeholders::_1);
                    _discovery_client = std::make_shared<DiscoveryClient>(ip, port, offline_cb);
                }
                else
                {
                    auto message_cb = std::bind(&Dispatcher::onMessage, _dispatcher.get(), std::placeholders::_1, std::placeholders::_2);
                    _rpc_client = ClientFactory::create(ip, port);
                    _rpc_client->setMessageCallback(message_cb);
                    _rpc_client->connect();
                }
            }

        public:
            // 封装接口调用
            // 同步
            bool call(const std::string &method, const Json::Value &params, Json::Value &result)
            {
                // 获取服务提供者：1. 服务发现；  2. 固定服务提供者
                BaseClient::ptr client = getClient(method);
                if (client.get() == nullptr)
                {
                    return false;
                }
                // 通过客户端连接,发送rpc请求
                return _caller->call(client->connection(), method, params, result);
            }
            // 异步 -- 这里返回给用户的是正文
            bool call(const std::string &method, const Json::Value &params, RpcCaller::JsonAsyncResponse &result)
            {
                BaseClient::ptr client = getClient(method);
                if (client.get() == nullptr)
                {
                    return false;
                }
                return _caller->call(client->connection(), method, params, result);
            }
            // 回调
            bool call(const std::string &method, const Json::Value &params, const RpcCaller::JsonResponseCallback &cb)
            {
                // 获取服务提供者：1. 服务发现；  2. 固定服务提供者
                BaseClient::ptr client = getClient(method);
                if (client.get() == nullptr)
                {
                    return false;
                }
                // 通过客户端连接,发送rpc请求
                return _caller->call(client->connection(), method, params, cb);
            }

        private:
            // 连接关闭, 删除池中的连接对象(服务下线的回调处理)
            void delClient(const Address &host)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                _rpc_clients.erase(host);
            }

            // 创建一个Client连接对象
            BaseClient::ptr newClient(const Address &host)
            {
                auto message_cb = std::bind(&Dispatcher::onMessage, _dispatcher.get(), std::placeholders::_1, std::placeholders::_2);
                auto client = ClientFactory::create(host.first, host.second);
                client->setMessageCallback(message_cb);
                client->connect();  // 连接提供服务的rpc服务器
                // 将client放进连接池
                putClient(host, client);
                return client;
            }

            void putClient(const Address &host, BaseClient::ptr &client)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                _rpc_clients.insert(std::make_pair(host, client));
            }

            // 通过addr获取client对象
            BaseClient::ptr getClient(const Address &host)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _rpc_clients.find(host);
                if (it == _rpc_clients.end())
                {
                    return BaseClient::ptr();
                }
                return it->second;
            }

            // 通过服务名称获取client
            BaseClient::ptr getClient(const std::string &method)
            {
                BaseClient::ptr client;
                if (_enableDiscovery)
                {
                    Address host; // 拿到服务提供者的 ip + port
                    // 通过服务发现机制找到host, 再通过getClient使用host找到client
                    bool ret = _discovery_client->serviceDiscovery(method, host);
                    if (ret == false)
                    {
                        ELOG("未找到对应服务的主机信息: %s", method.c_str());
                        return BaseClient::ptr();
                    }
                    client = getClient(host);
                    if (client.get() == nullptr)
                    {
                        // 没有这个client连接对象, 重新造一个(与该服务建立连接)
                        client = newClient(host); // 这里newClient就会创建一个与该服务提供者建立连接的Client
                    }
                }
                else
                {
                    client = _rpc_client;
                }
                return client;
            }

        private:
            // 自定义类型放进哈希表, 需要支持转换为数字(方便计算hash位置)
            struct AddressHash
            {
                size_t operator()(const Address &host) const
                {
                    std::string addr = host.first + std::to_string(host.second);
                    // c++11的仿函数对象hash--支持计算哈希值
                    return std::hash<std::string>{}(addr);
                }
            };

            bool _enableDiscovery;
            DiscoveryClient::ptr _discovery_client; // 服务发现客户端
            Requestor::ptr _requestor;
            RpcCaller::ptr _caller;
            Dispatcher::ptr _dispatcher;
            BaseClient::ptr _rpc_client; // 未启动服务发现(1v1)
            std::mutex _mutex;
            // <"127.0.0.1:8080", client1>
            std::unordered_map<Address, BaseClient::ptr, AddressHash> _rpc_clients; // (与rpc服务器地址, 建立连接的客户端)
            // 传递仿函数, 支持key转数字
        };

        // 4.topic客户端
        class TopicClient
        {
        public:
            using ptr = std::shared_ptr<TopicClient>;
            TopicClient(const std::string& ip, int port) 
                : _requestor(std::make_shared<Requestor>())
                , _dispatcher(std::make_shared<Dispatcher>())
                , _topic_manager(std::make_shared<TopicManager>(_requestor))
            {
                // 1.向dispatcher注册回调函数
                // 对主题响应的回调处理
                auto rsp_cb = std::bind(&Requestor::onResponse, _requestor.get(), std::placeholders::_1, std::placeholders::_2);
                // 对主题消息推送请求的回调处理
                auto msg_cb = std::bind(&TopicManager::onPublish, _topic_manager.get(), std::placeholders::_1, std::placeholders::_2);
                _dispatcher->registerHandler<BaseMessage>(MType::RSP_TOPIC, rsp_cb);
                _dispatcher->registerHandler<TopicRequest>(MType::REQ_TOPIC, msg_cb);
                // 2.设置客户端的回调函数
                _rpc_client = ClientFactory::create(ip, port);
                auto message_cb = std::bind(&Dispatcher::onMessage, _dispatcher.get(), std::placeholders::_1, std::placeholders::_2);
                _rpc_client->setMessageCallback(message_cb);
                _rpc_client->connect();
            }
        public:
            bool create(const std::string &key)
            {
                return _topic_manager->create(_rpc_client->connection(), key);
            }
            bool remove(const std::string &key)
            {
                return _topic_manager->remove(_rpc_client->connection(), key);
            }
            bool subscribe(const std::string &key, const TopicManager::SubCallback &cb)
            {
                return _topic_manager->subscribe(_rpc_client->connection(), key, cb);
            }
            bool cancel(const std::string &key)
            {
                return _topic_manager->cancel(_rpc_client->connection(), key);
            }
            bool publish(const std::string &key, const std::string &msg)
            {
                return _topic_manager->publish(_rpc_client->connection(), key, msg);
            }
            void shutdown()
            {
                _rpc_client->shutdown();
            }
        private:
            Requestor::ptr _requestor;
            TopicManager::ptr _topic_manager;
            Dispatcher::ptr _dispatcher;
            BaseClient::ptr _rpc_client;
        };
    }
}
